package com.css.login.server;

import com.caucho.hessian.server.HessianServlet;

import nl.justobjects.pushlet.core.Dispatcher;
import nl.justobjects.pushlet.core.Event;

@SuppressWarnings("serial")
public class LoginServiceImpl extends HessianServlet implements LoginService {
	/**
	 * 获取动态密码接口
	 * 
	 * @param uuid
	 * @return string
	 */
	public String getDynamicToken(String uuid) {
		// 生成token
		String token = generateRandomNum();
		// 写入缓存
		com.css.db.memcached.MemCachedFactory.set(token, uuid, 120);
		// 返回token值
		return token;
	}

	/**
	 * 动态密码获取用户id
	 * 
	 * @param token
	 * @return string
	 */
	public String getDynamicUserId(String token) {
		String uuid = (String) com.css.db.memcached.MemCachedFactory.get(token);
		// 清除缓存
		com.css.db.memcached.MemCachedFactory.delete(token);
		// 返回uuid
		return uuid;
	}

	/**
	 * 发送二维码token和uuid接口
	 * 
	 * @param token,uuid
	 * @return boolean
	 */
	public boolean sendQcToken(String token, String uuid) {
		String pushletId = (String) com.css.db.memcached.MemCachedFactory.get(token);
		if (pushletId == null) {
			return false;
		}
		// 次处将pushlet和uuid合并，调用前台方法加入id信息登录
		// String = "userId";
		Event event = Event.createDataEvent(pushletId);
		event.setField("uuid", uuid);
		com.css.db.memcached.MemCachedFactory.delete(token);
		Dispatcher.getInstance().multicast(event);
		return true;
	}

	private String generateRandomNum() {
		/**************************
		 * 生成6位动态密码 *
		 **************************/
		String num = "1234567890";
		int size = 6;
		char[] charArray = num.toCharArray();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < size; i++) {
			sb.append(charArray[((int) (Math.random() * 10000) % charArray.length)]);
		}
		return sb.toString();
	}

}
